/**
 * 预测图表轮播切换器
 * 实现左上角大图表与右上角小图表之间的轮播切换
 */

class ChartSwapper {
    constructor() {
        this.charts = {
            main: {
                id: 'predictionTempChart',
                container: null,
                instance: null,
                data: null,
                title: '预测温度传感器数据',
                type: 'temperature'
            },
            small1: {
                id: 'predictionLightChart', 
                container: null,
                instance: null,
                data: null,
                title: '预测光传感器数据',
                type: 'light'
            },
            small2: {
                id: 'predictionSoundChart',
                container: null,
                instance: null, 
                data: null,
                title: '预测声音传感器数据',
                type: 'sound'
            }
        };
        
        this.isSwapping = false;
        
        this.init();
    }

    init() {
        // 等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.setupSwapper());
        } else {
            this.setupSwapper();
        }
    }

    setupSwapper() {
        // 获取图表容器
        this.charts.main.container = document.getElementById(this.charts.main.id);
        this.charts.small1.container = document.getElementById(this.charts.small1.id);
        this.charts.small2.container = document.getElementById(this.charts.small2.id);

        if (!this.charts.main.container || !this.charts.small1.container || !this.charts.small2.container) {
            console.warn('[Chart Swapper] 等待图表容器加载...');
            setTimeout(() => this.setupSwapper(), 500);
            return;
        }

        // 添加点击事件
        this.addClickListeners();
        
        // 添加样式
        this.addSwapperStyles();
        
        console.log('[Chart Swapper] 图表轮播功能已初始化');
    }

    addClickListeners() {
        // 为每个图表容器添加点击事件
        Object.keys(this.charts).forEach(key => {
            const chart = this.charts[key];
            if (chart.container) {
                chart.container.style.cursor = 'pointer';
                chart.container.addEventListener('click', () => this.handleChartClick(key));
                
                // 添加悬停效果
                chart.container.addEventListener('mouseenter', () => this.addHoverEffect(chart.container));
                chart.container.addEventListener('mouseleave', () => this.removeHoverEffect(chart.container));
            }
        });
    }

    addHoverEffect(container) {
        if (!this.isSwapping) {
            container.style.transform = 'scale(1.02)';
            container.style.boxShadow = '0 4px 20px rgba(76, 175, 80, 0.3)';
            container.style.transition = 'all 0.3s ease';
        }
    }

    removeHoverEffect(container) {
        if (!this.isSwapping) {
            container.style.transform = 'scale(1)';
            container.style.boxShadow = 'none';
        }
    }

    handleChartClick(clickedKey) {
        if (this.isSwapping) {
            console.log('[Chart Swapper] 正在切换中，请稍候...');
            return;
        }

        // 如果点击的是主图表，不进行交换
        if (clickedKey === 'main') {
            console.log('[Chart Swapper] 点击了主图表，无需交换');
            return;
        }

        console.log(`[Chart Swapper] 点击了 ${clickedKey} 图表，与主图表进行交换`);
        this.swapWithMain(clickedKey);
    }

    async swapWithMain(targetKey) {
        if (this.isSwapping) return;
        
        this.isSwapping = true;
        
        try {
            // 保存当前的图表类型映射
            const currentMainType = this.charts.main.type;
            const targetType = this.charts[targetKey].type;
            
            console.log(`[Chart Swapper] 交换 ${targetType} 与 ${currentMainType}`);
            
            // 执行交换动画
            await this.performSwapAnimation(targetKey);
            
            // 交换图表内容
            this.swapChartContents(targetKey, currentMainType, targetType);
            
            console.log('[Chart Swapper] 图表交换完成');
            
        } catch (error) {
            console.error('[Chart Swapper] 交换失败:', error);
        } finally {
            this.isSwapping = false;
        }
    }



    async performSwapAnimation(targetKey) {
        const mainContainer = this.charts.main.container;
        const targetContainer = this.charts[targetKey].container;

        // 第一阶段：淡出动画
        [mainContainer, targetContainer].forEach(container => {
            container.style.transition = 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
            container.style.transform = 'scale(0.95)';
            container.style.opacity = '0.4';
            container.style.filter = 'blur(2px)';
        });

        // 等待淡出动画完成
        await new Promise(resolve => setTimeout(resolve, 300));

        // 第二阶段：淡入动画
        [mainContainer, targetContainer].forEach(container => {
            container.style.transform = 'scale(1)';
            container.style.opacity = '1';
            container.style.filter = 'blur(0px)';
        });

        // 等待淡入动画完成
        await new Promise(resolve => setTimeout(resolve, 300));

        // 重置样式
        [mainContainer, targetContainer].forEach(container => {
            container.style.transition = '';
            container.style.transform = '';
            container.style.filter = '';
        });
    }

    swapChartContents(targetKey, currentMainType, targetType) {
        // 清除被交换的图表实例
        const mainContainer = this.charts.main.container;
        const targetContainer = this.charts[targetKey].container;
        
        // 获取当前实例并销毁
        const mainInstance = echarts.getInstanceByDom(mainContainer);
        const targetInstance = echarts.getInstanceByDom(targetContainer);
        
        if (mainInstance) mainInstance.dispose();
        if (targetInstance) targetInstance.dispose();
        
        // 清空容器
        mainContainer.innerHTML = '';
        targetContainer.innerHTML = '';
        
        // 重设容器最小尺寸
        mainContainer.style.minWidth = '100%';
        mainContainer.style.minHeight = '280px';
        
        targetContainer.style.minWidth = '100%';
        targetContainer.style.minHeight = '280px';
        
        // 交换图表类型
        this.charts.main.type = targetType;
        this.charts[targetKey].type = currentMainType;
        
        // 重新创建图表
        setTimeout(() => {
            this.recreateSwappedCharts(targetKey, currentMainType, targetType);
        }, 100);
    }

    recreateSwappedCharts(targetKey, currentMainType, targetType) {
        // 根据新的类型重新创建图表
        const mainContainerId = this.charts.main.id;
        const targetContainerId = this.charts[targetKey].id;
        
        // 创建新的图表映射
        const newMapping = {
            main: targetType,
            [targetKey]: currentMainType
        };
        
        // 发送图表重建事件
        const event = new CustomEvent('chartSwapComplete', {
            detail: { 
                swapMode: true,
                targetKey: targetKey,
                newMapping: newMapping,
                containers: {
                    main: this.charts.main.container,
                    [targetKey]: this.charts[targetKey].container
                }
            }
        });
        
        document.dispatchEvent(event);
        
        console.log('[Chart Swapper] 图表交换映射:', newMapping);
    }

    addSwapperStyles() {
        if (document.getElementById('chart-swapper-styles')) return;
        
        const style = document.createElement('style');
        style.id = 'chart-swapper-styles';
        style.textContent = `
            .chart-container {
                position: relative;
                transition: all 0.3s ease;
                border-radius: 8px;
                overflow: hidden;
            }
            
            /* 小图表的放大提示 */
            .chart-container.chart-small::before {
                content: '';
                position: absolute;
                top: 8px;
                right: 8px;
                width: 30px;
                height: 20px;
                background: rgba(76, 175, 80, 0.9);
                border-radius: 10px;
                opacity: 0;
                transition: all 0.3s ease;
                z-index: 100;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            
            .chart-container.chart-small::after {
                content: '放大显示';
                position: absolute;
                top: 8px;
                right: 8px;
                width: 30px;
                height: 20px;
                color: white;
                font-size: 9px;
                display: flex;
                align-items: center;
                justify-content: center;
                opacity: 0;
                transition: all 0.3s ease;
                z-index: 101;
                pointer-events: none;
                font-weight: bold;
            }
            
            .chart-container.chart-small:hover::before,
            .chart-container.chart-small:hover::after {
                opacity: 1;
            }
            
            /* 大图表的提示 */
            .chart-container.chart-large::before {
                content: '';
                position: absolute;
                top: 8px;
                right: 8px;
                width: 30px;
                height: 20px;
                background: rgba(158, 158, 158, 0.8);
                border-radius: 10px;
                opacity: 0;
                transition: all 0.3s ease;
                z-index: 100;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            
            .chart-container.chart-large::after {
                content: '已放大';
                position: absolute;
                top: 8px;
                right: 8px;
                width: 30px;
                height: 20px;
                color: white;
                font-size: 9px;
                display: flex;
                align-items: center;
                justify-content: center;
                opacity: 0;
                transition: all 0.3s ease;
                z-index: 101;
                pointer-events: none;
                font-weight: bold;
            }
            
            .chart-container.chart-large:hover::before,
            .chart-container.chart-large:hover::after {
                opacity: 1;
            }
            
            .chart-swapping {
                pointer-events: none;
            }
        `;
        document.head.appendChild(style);
    }

    // 公共方法：获取当前图表映射
    getCurrentMapping() {
        const mapping = {};
        Object.keys(this.charts).forEach(key => {
            mapping[key] = this.charts[key].type;
        });
        return mapping;
    }

    // 公共方法：检查是否正在切换
    isCurrentlySwapping() {
        return this.isSwapping;
    }
}

// 创建全局实例
window.ChartSwapper = new ChartSwapper();

// 导出到全局作用域
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ChartSwapper;
} 